package com.chuangke.mds.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.chuangke.admin.entity.SysUser;
import com.chuangke.context.service.ContextService;
import com.chuangke.mds.entity.TechnologyProcess;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.chuangke.admin.data.builder.DictDataBuilder;
import com.chuangke.common.constant.SysDictTypeConstants;
import com.chuangke.common.data.builder.DataBuildConfig;
import com.chuangke.common.data.builder.DataBuilder;
import com.chuangke.common.db.page.CkPageQuery;
import com.chuangke.common.idgen.IdManager;
import com.chuangke.common.trans.annotation.TransResult;
import com.chuangke.mds.dao.ProductDao;
import com.chuangke.mds.entity.Product;
import com.chuangke.mds.service.ProductService;

import cn.hutool.core.util.StrUtil;

@Service
@Transactional(rollbackFor = Throwable.class)
public class ProductImpl implements ProductService {
	@Autowired
	private ContextService contextService;
	@Autowired
	private ProductDao productDao ;
//	@Autowired
//	private ContextService contextService;
	
	@Override
	public String save(Product model) {
		return saveOrUpdate(model);
	}
	
	@Override
	public void update(Product model) {
		saveOrUpdate(model);
	}

	@Override
	public String saveOrUpdate(Product model) {
		if (StrUtil.isBlank(model.getId())) {
			doSave(model) ;
		}else{
			doUpdate(model) ;
		}
		return model.getId() ;
	}
	
	private void doSave(Product model) {
		model.setId(IdManager.nextId());
		productDao.save(model) ;

	}

	
	private void doUpdate(Product model) {
//		ZchkclProduct delay = taskDelayDao.getOne(new QueryWrapper<ZchkclProduct>().lambda().eq(ZchkclProduct::getBillId, model.getBillId())) ;
//		if(!OrderStatusEnum.EDIT.getCode().equals(delay.getStatus())) {
//			throw new ChuangkeException("非编制状态，不允许编辑") ;
//		}
		productDao.updateById(model) ;
	}

	@Override
	public void delete(List<String> billIds) {
		QueryWrapper<Product> qw = new QueryWrapper<Product>() ;
		qw.lambda().in(Product::getId, billIds) ;
//		List<ZchkclProduct> list = taskDelayDao.list(qw) ;
//		for(ZchkclProduct delay : list) {
//			if(!FlowConstant.STATUS_BZZ.equals(delay.getStatus())) {
//				throw new ChuangkeException("只能删除编制中的业务单据") ;
//			}
//		}
		
        productDao.remove(new QueryWrapper<Product>().lambda().in(Product::getId, billIds));
//        flowInstanceService.deleteInstance(billIds);
	}

	@Override
	@TransResult
	public Product load(String billId) {
		Product product = productDao.getOne(new QueryWrapper<Product>().lambda().eq(Product::getId, billId)) ;
		ArrayList<Product> list = new ArrayList<>();
		list.add(product) ;
		DataBuilder.of(list).appendBuilder(new DictDataBuilder(SysDictTypeConstants.ZCHKCL_PRODUCT_TYPE), new DataBuildConfig("typeId", "typeName") ).build();
		return product;
	}

	@Override
	@TransResult
	public IPage<Product> page(CkPageQuery page) {
		QueryWrapper<Product> qw = new QueryWrapper<>();
		if(!StringUtils.isEmpty(page.getAsString("name"))) {
			qw.lambda().like(Product::getName, page.getAsString("name")) ;
		}
		if (!StringUtils.isEmpty(page.getAsString("type"))) {
			qw.lambda().eq(Product::getTypeId, page.getAsString("type"));
		}
//		qw.lambda().le(Product::getClassification, page.getAsString("classification"));
		qw.lambda().in(Product::getClassification,  (List<String>) page.get("classification"));
		qw.lambda().orderByDesc(Product::getCreatedAt) ;

		SysUser user= contextService.getCurrentUser();
		String userId = user.getId();
		String isAdded = page.getAsString("isAdded");
		if ((!"admin".equals(userId))&& "1".equals(isAdded)) {
			qw.lambda().eq(Product::getCreatedBy, userId);
		}

		IPage<Product> resultPage = productDao.page(page.getPage(),qw);
		List<Product> records = resultPage.getRecords();
		DataBuilder.of(records).appendBuilder(new DictDataBuilder("mds_product_type","bean"), new DataBuildConfig("typeId", "typeName")).build();

		resultPage.setRecords(records);

		return resultPage;
	}

	@Override
	public List<Product> getAll() {
		return productDao.list();
	}

//	@Override
//	public void submitBatch(List<String> orderIdList) {
//		validate4submit(orderIdList) ;
//		OrderFlowUtilsV2.submitBatch(taskDelayDao, orderIdList);
//		OrderFlowUtilsV2.submitBatch(taskDelayDetailDao, orderIdList);
//	}
//
//	@Override
//	public void cancelSubmitBatch(List<String> orderIdList) {
//		OrderFlowUtilsV2.cancelSubmitBatch(taskDelayDao, orderIdList);
//		OrderFlowUtilsV2.cancelSubmitBatch(taskDelayDetailDao, orderIdList);
//	}
//
//	@Override
//	public void rejectBatch(List<String> orderIdList) {
//		OrderFlowUtilsV2.rejectBatch(taskDelayDao, orderIdList);
//		OrderFlowUtilsV2.rejectBatch(taskDelayDetailDao, orderIdList);
//	}
//
//	@Override
//	public void completeBatch(List<String> orderIdList) {
//		OrderFlowUtilsV2.completeBatch(taskDelayDao, orderIdList);
//		OrderFlowUtilsV2.completeBatch(taskDelayDetailDao, orderIdList);
//
//		QueryWrapper<ZchkclProductDetail> qw = new QueryWrapper<>();
//	    qw.lambda().in(ZchkclProductDetail::getBillId, orderIdList) ;
//		List<ZchkclProductDetail> details = taskDelayDetailDao.list(qw) ;
//
//		for(ZchkclProductDetail p : details) {
//			taskService.delayTask(p.getTaskId(),p.getOldEndDate(), p.getNowEndDate(), p.getDelayDesc());
//		}
//	}
	
//	@Autowired
//	private FlowTaskService flowTaskService;
//
//	@Override
//	public FlowAuditResult submit(List<FlowHandler> handlerList) {
//		if (CollectionUtils.isEmpty(handlerList)) {
//			throw new ChuangkeException("请选择数据");
//		}
//
//		List<String> billIds = handlerList.stream().map(FlowHandler::getBusinessKey).toList();
//		validate4submit(billIds) ;
//
//		return flowTaskService.complete(handlerList);
//	}
//
//	private void validate4submit(List<String> billIds) {
//		QueryWrapper<ZchkclProduct> qw1 = new QueryWrapper<>();
//		qw1.lambda().in(ZchkclProduct::getBillId, billIds);
//		List<ZchkclProduct> delayList = taskDelayDao.list(qw1);
//
//		for(ZchkclProduct delay : delayList) {
//			if(!FlowConstant.STATUS_BZZ.equals(delay.getStatus())) {
//				throw new ChuangkeException("非编辑中业务单据，不能提交") ;
//			}
//			Task task = taskQueryService.load(delay.getTaskId()) ;
//			if(task == null){
//				throw new ChuangkeException("当前督办不存在，不能申请延期") ;
//			}
//			if(!TaskConstant.TASK_RUNNING_STATUS_LIST.contains(task.getStatus())){
//				throw new ChuangkeException("当前督办未在运行中，不能申请延期") ;
//			}
//		}
//
//		QueryWrapper<ZchkclProductDetail> qw = new QueryWrapper<>();
//		qw.lambda().in(ZchkclProductDetail::getBillId, billIds);
//		List<ZchkclProductDetail> delayDetailList = taskDelayDetailDao.list(qw);
//
//		for(ZchkclProductDetail detail : delayDetailList) {
//			QueryWrapper<ZchkclProduct> qw2 = new QueryWrapper<>();
//			qw2.lambda().ne(ZchkclProduct::getBillId, detail.getBillId());
//			qw2.lambda().eq(ZchkclProduct::getStatus, FlowConstant.STATUS_SPZ);
//			qw2.lambda().exists("select 1 from oa_task_delay_detail where oa_task_delay_detail.task_id={0} "
//					+ "and oa_task_delay_detail.bill_id=oa_task_delay.bill_id", detail.getTaskId()) ;
//			List<ZchkclProduct> list = taskDelayDao.list(qw2);
//
//			if(CollectionUtils.isNotEmpty(list)){
//				throw new ChuangkeException(String.format("督办【%s】存在审批中的延期申请", detail.getName())) ;
//			}
//		}
//
//		List<String> taskIds = delayDetailList.stream().map(ZchkclProductDetail::getTaskId).toList() ;
//		TaskUtil.validateIsLastLevelDoBis(taskDao,taskIds) ;
//	}
//
//	@Override
//	public FlowAuditResult saveAndSubmit(ZchkclProduct model) {
//		String billId = this.save(model) ;
//
//		FlowHandler fh = new FlowHandler() ;
//		fh.setAudit(FlowConstant.VAR_AUDIT_OPT_AGREE);
//		fh.setBusinessKey(billId);
//		fh.setUserId(SecurityUtils.getUserId());
//		return this.submit(Arrays.asList(fh));
//	}

}
